<!--  -->
<template>
  <div class="search-suggest">
    <van-cell v-for="(text,index) in list" :key="index"
      class="history-cell" @click="$emit('search',text)">
      <template #title >
          <span v-html="highLight(text)"></span>
      </template>
      <template #icon>
        <i class="iconfont icon-sousuo"></i>
      </template>
    </van-cell>
  </div>
</template>

<script>
import { getSearchSuggestions } from '@/api/search.js'
import { debounce } from 'lodash'
export default {
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      list: []
    }
  },
  watch: {
    searchText: {
      handler: debounce(function (val) {
        this.loadSearchSuggestions(val)
      }, 300),
      immediate: true
    }
  },
  methods: {
    async loadSearchSuggestions (val) {
      this.list = []
      try {
        const res = await getSearchSuggestions(val)
        this.list.push(...res.data.data.options)
        // console.log(this.list)
      } catch (error) {
        console.log(error)
      }
    },
    highLight (text) {
      const str = `<span class='highLight'>${this.searchText}</span>`
      const reg = new RegExp(this.searchText, 'gi')
      return text.replace(reg, str)
    }
  }
}
</script>

<style  scoped lang='less'>
.history-cell {
  font-size: 30px;
  i.iconfont {
    font-size: 30px;
    margin-right: 15px;
  }
  /deep/.highLight {
      color:rgb(241, 118, 118)
  }
}
</style>
